<style media="screen" type="text/css">/*<![CDATA[*/@import 'stylesheet.css';/*]]>*/</style>
<style media="screen" type="text/css">/*<![CDATA[*/@import 'demo.css';/*]]>*/</style>
<style type="text/css">#title,#glyphs p{font-family:"LED"}</style>



<script>
function digits(obj, e, allowDecimal, allowNegative)
{
 var key;
 var isCtrl = false;
 var keychar;
 var reg;
   
 if(window.event) {
  key = e.keyCode;
  isCtrl = window.event.ctrlKey
 }
 else if(e.which) {
  key = e.which;
  isCtrl = e.ctrlKey;
 }
  
 if (isNaN(key)) return true;
  
 keychar = String.fromCharCode(key);
  
 // check for backspace or delete, or if Ctrl was pressed
 if (key == 8 || isCtrl)
 {
  return true;
 }

 reg = /^\d+$/;
 
 if(allowDecimal==true && reg.test(keychar)==false){
	 if(keychar!='.')
	 	return false;
 }
 
 var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
 var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;

 if(allowDecimal == true){
	 var n = obj.value.split('.');
	 if(n[1].length >= 4) return false;
 }
 
 return isFirstN || isFirstD || reg.test(keychar);
}

function validate(form){
	choose_type = false;
	var rads = document.getElementsByName('trade_type');
	for (i=0; i < rads.length; i++)
	if (rads[i].checked){
		choose_type = true;
		var trade_type = rads[i].value;
	}
       	
	if(choose_type == false){
		alert(document.getElementById('msg1').value);
		return false;
	}

	if(document.getElementById('queue').value >= 1 && trade_type=="sell"){
		alert(document.getElementById('msg6').value);
		return false;
	}else if(document.getElementById('ttl_sell').value >= 5){
		alert(document.getElementById('msg8').value);
		return false;
	}

	if(document.getElementById('qty').value == ''){
		alert(document.getElementById('msg2').value);
		return false;
	}else if(document.getElementById('qty').value < 100 && parseInt(document.getElementById('limit').value) >= 100){
		alert(document.getElementById('msg5').value);
		return false;
	}else if(parseInt(document.getElementById('qty').value) > parseInt(document.getElementById('limit').value)  && trade_type=="sell"){
		alert(document.getElementById('msg7').value);
		return false;
	}

	if(document.getElementById('price').value == ''){
		alert(document.getElementById('msg3').value);
		return false;
	}
	//alert('Trading platform under maintenance, please try again later!');
	//return false;
	return confirm(document.getElementById('msg4').value);
}
</script>

<?php
require_once("inc.member.php");

$this_title="$vars[member_title] &raquo; ".__("Market");
$page_title=__("Market");
$content_title=__("Market");

$purchase_share=$vars["file"]["member"]["purchase_share"];
$sell_share=$vars["file"]["member"]["sell_share"];

$item_per_page=$vars["user_item_per_page"];

$user_info = ajax_check_user($uid);

$msg="";
if($_POST['__trade']){
	if(is_numeric($_POST['qty'])==false){
		$msg = "<font color='red'>Invalid input!</font>";
	}else{		
		if($_POST['trade_type']=='buy'){
			$cdate = date('Y-m-d H:i:s');
			$qty = $_POST['qty'];
			$price = number_format($_POST['buy_price'],3);
			$amount = 0;
			
			$qty_balance = mysql_result(mysql_query("select balance-buy_balance from gg_share_target where share_price=".$price), 0) or 0;
			if($qty>$qty_balance){
				$msg = "<font color='red'>".replace_tag(__("Balance for <%price%> only have <%qty%>"), array("<%price%>"=>$price, "<%qty%>"=>$qty_balance))."</font>";
			}else{
				//only php 5.3 above can use PHP_ROUND_HALF_UP
				//$amount = round($qty * $price, 2, PHP_ROUND_HALF_UP);
				$amount = (ceil(($qty * $price) * 100) / 100);
				$wallet_balance = 0;
				if($_POST['payment']=="mwallet"){
					$wallet_balance = mysql_result(mysql_query("select mwallet from gg_users where id=".$uid), 0) or 0;
				}elseif($_POST['payment']=="ewallet"){
					$wallet_balance = mysql_result(mysql_query("select ewallet from gg_users where id=".$uid), 0) or 0;
				}
				
				$new_balance = $wallet_balance - $amount;
				if($amount>$wallet_balance){
					$msg = "<font color='red'>".__('Not enough point to buy!')."</font>";
				}else{
					mysql_query("update gg_share_target set buy_balance=buy_balance+".$qty." where share_price=".$price);
								
					if($_POST['payment']=="mwallet"){
						mysql_query("update gg_users set mwallet=".$new_balance." where id=".$uid);
						mysql_query("insert into gg_member_mwallet_record (uid,type,amount,bal,descr,cdate) values (".$uid.",'debit',".$amount.",".$new_balance.",'Buy ordinary share. ".$qty." X ".$price." = ".$amount."','".$cdate."')");
					}else{
						mysql_query("update gg_users set ewallet=".$new_balance." where id=".$uid);
						mysql_query("insert into gg_member_ewallet_record (uid,type,amount,bal,descr,cdate) values (".$uid.",'debit',".$amount.",".$new_balance.",'Buy ordinary share. ".$qty." X ".$price." = ".$amount."','".$cdate."')");
					}
					mysql_query("insert into gg_share_trading (uid,price,qty,match_qty,type,payment_type,cdate) values (".$uid.",".$price.",".$qty.",0,'buy','".$_POST['payment']."','".$cdate."')");
					$id = mysql_insert_id();
					$match_qty = 0;
					
					while($qty>0){
						$sell_rs = mysql_query("select * from gg_share_trading where price=".$price." and type='sell' and qty>match_qty order by cdate limit 1");
						$num_rows = mysql_num_rows($sell_rs);
						if($num_rows == NULL){
							$qty=0;
						}else{
							$buy_qty = 0;
							$sell = mysql_fetch_assoc($sell_rs);
							$sell_balance = $sell['qty']-$sell['match_qty'];
							if($sell_balance>=$qty){
								$buy_qty = $qty;
							}else{
								$buy_qty = $sell_balance;
							}
							
							$qty -= $buy_qty;
							$match_qty += $buy_qty;
							//$sell_amount = number_format($buy_qty*$sell['price'],2, '.', '');
							$sell_amount = (floor(($buy_qty*$sell['price']) * 100) / 100);
								
							mysql_query("update gg_share_trading set match_qty=match_qty+".$buy_qty." where id=".$sell['id']);
							mysql_query("insert into gg_share_trading_ledger (trading_id,uid,buy_uid,sell_uid,price,qty,type,cdate) values (".$sell['id'].",".$uid.",".$uid.",".$sell['uid'].",".$sell['price'].",".$buy_qty.",'buy','".$cdate."')");
							mysql_query("insert into gg_share_trading_ledger (trading_id,uid,buy_uid,sell_uid,price,qty,type,cdate) values (".$sell['id'].",".$sell['uid'].",".$uid.",".$sell['uid'].",".$sell['price'].",".$buy_qty.",'sell','".$cdate."')");
								
							$sell_ewallet_balance = mysql_result(mysql_query("select ewallet from gg_users where id=".$sell['uid']), 0) or 0;
							$sell_mwallet_balance = mysql_result(mysql_query("select mwallet from gg_users where id=".$sell['uid']), 0) or 0;
							$sell_ewallet_balance += $sell_amount;
							mysql_query("insert into gg_member_ewallet_record (uid,type,amount,bal,descr,cdate) values (".$sell['uid'].",'credit',".$sell_amount.",".$sell_ewallet_balance.",'Sell ordinary share. ".$buy_qty." X ".$sell['price']." = ".$sell_amount."','".$cdate."')");
							//only php 5.3 above can use PHP_ROUND_HALF_UP
							//$sell_fee = round($sell_amount*0.1, 2, PHP_ROUND_HALF_UP);
							// no more processing fees except IND
							if($user_info['user_detail']['country']=='IND'){
								$sell_fee = (ceil(($sell_amount*0.1) * 100) / 100);
								$sell_ewallet_balance -= $sell_fee;
								mysql_query("insert into gg_member_ewallet_record (uid,type,amount,bal,descr,cdate) values (".$sell['uid'].",'debit',".$sell_fee.",".$sell_ewallet_balance.",'Sell ordinary share. ".$sell_amount." X 10% = ".$sell_fee."','".$cdate."')");
							}
							//30% repurchase share
							$repurchase = (ceil((($sell_amount-$sell_fee)*0.3) * 100) / 100);
							$sell_ewallet_balance -= $repurchase;
							$sell_mwallet_balance += $repurchase;
							mysql_query("insert into gg_member_ewallet_record (uid,type,amount,bal,descr,cdate) values (".$sell['uid'].",'debit',".$repurchase.",".$sell_ewallet_balance.",'30% convert to share trading account.','".$cdate."')");
							mysql_query("insert into gg_member_mwallet_record (uid,type,amount,bal,descr,cdate) values (".$sell['uid'].",'credit',".$repurchase.",".$sell_mwallet_balance.",'30% convert from e-wallet account.','".$cdate."')");
							mysql_query("update gg_users set ewallet=".$sell_ewallet_balance.",mwallet=".$sell_mwallet_balance." where id=".$sell['uid']);
						}				
					}
					
					if($match_qty>0){
						mysql_query("update gg_share_trading set match_qty=".$match_qty." where id=".$id);
						
						if($_POST['payment']=="ewallet"){
							$swallet_balance = mysql_result(mysql_query("select swallet from gg_users where id=".$uid), 0) or 0;
							$swallet_balance += $match_qty;
							mysql_query("insert into gg_member_swallet_record (uid,type,amount,bal,descr,cdate) values (".$uid.",'credit',".$match_qty.",".$swallet_balance.",'Buy ordinary share.','".$cdate."')");
							mysql_query("update gg_users set swallet=".$swallet_balance." where id=".$uid);
						}else{
							$s2wallet_balance = mysql_result(mysql_query("select s2wallet from gg_users where id=".$uid), 0) or 0;
							$s2wallet_balance += $match_qty;
							$trade_date  = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")+7, date("Y")));
							mysql_query("insert into gg_share (uid,total_unit,buy_price,buy_date,trade_date) values (".$uid.",".$match_qty.",".$price.",'".$cdate."','".$trade_date."')");
							mysql_query("update gg_users set s2wallet=".$s2wallet_balance." where id=".$uid);
						}
					}
				}
			}
		}
		
		if($_POST['trade_type']=='sell'){
			$cdate = date('Y-m-d H:i:s');
			$qty = $_POST['qty'];
			$price = number_format($_POST['price'],3);
			$sbalance = mysql_result(mysql_query("select swallet from gg_users where id=".$uid), 0) or 0;
			$new_sbalance = $sbalance - $qty;
			if($qty>$sbalance){
				$msg = "<font color='red'>Not enough share quantity to sell!</font>";
			}else{
				$qty_balance = mysql_result(mysql_query("select balance-sell_balance from gg_share_target where share_price=".$price), 0) or 0;
				if($qty>$qty_balance){
					$msg = "<font color='red'>".replace_tag(__("Balance for <%price%> only have <%qty%>"), array("<%price%>"=>$price, "<%qty%>"=>$qty_balance))."</font>";
				}else{	
					mysql_query("update gg_share_target set sell_balance=sell_balance+".$qty." where share_price=".$price);
					
					mysql_query("update gg_users set swallet=".$new_sbalance." where id=".$uid);
					mysql_query("insert into gg_member_swallet_record (uid,type,amount,bal,descr,cdate) values (".$uid.",'debit',".$qty.",".$new_sbalance.",'Sell ordinary share. ".$qty." with price ".$price."','".$cdate."')");
					mysql_query("insert into gg_share_trading (uid,price,qty,match_qty,type,payment_type,cdate) values (".$uid.",".$price.",".$qty.",0,'sell','swallet','".$cdate."')");
					$id = mysql_insert_id();
					$match_qty = 0;
					
					while($qty>0){
						$buy_rs = mysql_query("select * from gg_share_trading where price=".$price." and type='buy' and qty>match_qty order by cdate limit 1");
						$num_rows = mysql_num_rows($buy_rs);
						if($num_rows == NULL){
							$qty=0;
						}else{
							$sell_qty = 0;
							$buy = mysql_fetch_assoc($buy_rs);
							$buy_balance = $buy['qty']-$buy['match_qty'];
							if($buy_balance>=$qty){
								$sell_qty = $qty;
							}else{
								$sell_qty = $buy_balance;
							}
							
							$qty -= $sell_qty;
							$match_qty += $sell_qty;
							//$sell_amount = number_format($sell_qty*$buy['price'],2, '.', '');
							$sell_amount = (floor(($sell_qty*$buy['price']) * 100) / 100);
								
							mysql_query("update gg_share_trading set match_qty=match_qty+".$sell_qty." where id=".$buy['id']);
							mysql_query("insert into gg_share_trading_ledger (trading_id,uid,buy_uid,sell_uid,price,qty,type,cdate) values (".$buy['id'].",".$uid.",".$buy['uid'].",".$uid.",".$buy['price'].",".$sell_qty.",'sell','".$cdate."')");
							mysql_query("insert into gg_share_trading_ledger (trading_id,uid,buy_uid,sell_uid,price,qty,type,cdate) values (".$buy['id'].",".$buy['uid'].",".$buy['uid'].",".$uid.",".$buy['price'].",".$sell_qty.",'buy','".$cdate."')");
								
							$sell_ewallet_balance = mysql_result(mysql_query("select ewallet from gg_users where id=".$uid), 0) or 0;							
							$sell_mwallet_balance = mysql_result(mysql_query("select mwallet from gg_users where id=".$uid), 0) or 0;
							$sell_ewallet_balance += $sell_amount;
							mysql_query("insert into gg_member_ewallet_record (uid,type,amount,bal,descr,cdate) values (".$uid.",'credit',".$sell_amount.",".$sell_ewallet_balance.",'Sell ordinary share. ".$sell_qty." X ".$buy['price']." = ".$sell_amount."','".$cdate."')");
							//only php 5.3 above can use PHP_ROUND_HALF_UP
							//$sell_fee = round($sell_amount*0.1, 2, PHP_ROUND_HALF_UP);
							// no more processing fees except IND
							if($user_info['user_detail']['country']=='IND'){
								$sell_fee = (ceil(($sell_amount*0.1) * 100) / 100);
								$sell_ewallet_balance -= $sell_fee;
								mysql_query("insert into gg_member_ewallet_record (uid,type,amount,bal,descr,cdate) values (".$uid.",'debit',".$sell_fee.",".$sell_ewallet_balance.",'Sell ordinary share. ".$sell_amount." X 10% = ".$sell_fee."','".$cdate."')");
							}
							//30% repurchase share
							$repurchase = (ceil((($sell_amount-$sell_fee)*0.3) * 100) / 100);
							$sell_ewallet_balance -= $repurchase;
							$sell_mwallet_balance += $repurchase;
							mysql_query("insert into gg_member_ewallet_record (uid,type,amount,bal,descr,cdate) values (".$uid.",'debit',".$repurchase.",".$sell_ewallet_balance.",'30% convert to share trading account.','".$cdate."')");
							mysql_query("insert into gg_member_mwallet_record (uid,type,amount,bal,descr,cdate) values (".$uid.",'credit',".$repurchase.",".$sell_mwallet_balance.",'30% convert from e-wallet account.','".$cdate."')");
							mysql_query("update gg_users set ewallet=".$sell_ewallet_balance.",mwallet=".$sell_mwallet_balance." where id=".$uid);
							
							if($buy['payment_type']=="mwallet"){
								$s2wallet_balance = mysql_result(mysql_query("select s2wallet from gg_users where id=".$buy['uid']), 0) or 0;
								$s2wallet_balance += $sell_qty;
								$trade_date  = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")+7, date("Y")));
								mysql_query("insert into gg_share (uid,total_unit,buy_price,buy_date,trade_date) values (".$buy['uid'].",".$sell_qty.",".$price.",'".$cdate."','".$trade_date."')");
								mysql_query("update gg_users set s2wallet=".$s2wallet_balance." where id=".$buy['uid']);
							}else{
								$swallet_balance = mysql_result(mysql_query("select swallet from gg_users where id=".$buy['uid']), 0) or 0;
								$swallet_balance += $sell_qty;
								mysql_query("insert into gg_member_swallet_record (uid,type,amount,bal,descr,cdate) values (".$buy['uid'].",'credit',".$sell_qty.",".$swallet_balance.",'Buy ordinary share.','".$cdate."')");
								mysql_query("update gg_users set swallet=".$swallet_balance." where id=".$buy['uid']);
							}
						}				
					}
					
					if($match_qty>0)
						mysql_query("update gg_share_trading set match_qty=".$match_qty." where id=".$id);
				}
			}
		}
	}
}

if($_GET['action']=="trade" || !$_GET['action']){
 
   	$count_sql = "SELECT count(*) FROM $db->share_trading WHERE qty>match_qty AND type IN ('buy','sell') AND uid=".$uid;
	$record_sql = "SELECT * FROM $db->share_trading WHERE qty>match_qty AND type IN ('buy','sell') AND uid=".$uid." ORDER BY id LIMIT <%limit_start%>, <%limit%>";
	
}elseif($_GET['action']=="cancel_order"){
	if($_GET['order_id']>0){
		$sql = "SELECT * FROM $db->share_trading WHERE type IN ('sell','buy') AND match_qty=0 AND id=".$_GET['order_id'];
		$q = mysql_query($sql);
		if(mysql_num_rows($q)>0){
			$cdate = date('Y-m-d H:i:s');
			mysql_query("UPDATE $db->share_trading SET type='cancel' WHERE id=".$_GET['order_id']);
			
			$share = mysql_fetch_assoc($q);
			if($share['type']=="buy"){
				if($share['payment_type']=="mwallet"){
					$mwallet_balance = mysql_result(mysql_query("select mwallet from gg_users where id=".$share['uid']), 0) or 0;
					$mwallet_balance += $share['qty']*$share['price'];
					mysql_query("update gg_users set mwallet=".$mwallet_balance." where id=".$share['uid']);
					mysql_query("insert into gg_member_mwallet_record (uid,type,amount,bal,descr,cdate) values (".$share['uid'].",'credit',".($share['qty']*$share['price']).",".$mwallet_balance.",'Cancel buy order.','".$cdate."')");
				}else{
					$ewallet_balance = mysql_result(mysql_query("select ewallet from gg_users where id=".$share['uid']), 0) or 0;
					$ewallet_balance += $share['qty']*$share['price'];
					mysql_query("update gg_users set ewallet=".$ewallet_balance." where id=".$share['uid']);
					mysql_query("insert into gg_member_ewallet_record (uid,type,amount,bal,descr,cdate) values (".$share['uid'].",'credit',".($share['qty']*$share['price']).",".$ewallet_balance.",'Cancel buy order.','".$cdate."')");
				}
				
				mysql_query("update gg_share_target set buy_balance=buy_balance-".$share['qty']." where share_price=".$share['price']);
			}
			
			if($share['type']=="sell"){
				$swallet_balance = mysql_result(mysql_query("select swallet from gg_users where id=".$share['uid']), 0) or 0;
				$swallet_balance += $share['qty'];
				mysql_query("update gg_users set swallet=".$swallet_balance." where id=".$share['uid']);
				mysql_query("insert into gg_member_swallet_record (uid,type,amount,bal,descr,cdate) values (".$share['uid'].",'credit',".$share['qty'].",".$swallet_balance.",'Cancel sell order.','".$cdate."')");

				mysql_query("update gg_share_target set sell_balance=sell_balance-".$share['qty']." where share_price=".$share['price']);
			}
		}
	}
	
   	$count_sql = "SELECT count(*) FROM $db->share_trading WHERE type IN ('sell','buy') AND qty>match_qty AND uid=".$uid;
	$record_sql = "SELECT * FROM $db->share_trading WHERE type IN ('sell','buy') AND qty>match_qty AND uid=".$uid." ORDER BY id LIMIT <%limit_start%>, <%limit%>";
	
}elseif($_GET['action']=="share"){
 
   	$count_sql = "SELECT count(*) FROM $db->share WHERE trade_date>'".date('Y-m-d')."' AND status=0 AND uid=".$uid;
	$record_sql = "SELECT * FROM $db->share WHERE trade_date>'".date('Y-m-d')."' AND status=0 AND uid=".$uid." ORDER BY id LIMIT <%limit_start%>, <%limit%>";
	
}elseif($_GET['action']=="sell"){
	if($_GET['sell_id']>0){
		$sql = "SELECT id FROM $db->share WHERE status=0 AND replica=0 AND uid=".$uid." AND id=".$_GET['sell_id'];
		$q = mysql_query($sql);
		if(mysql_num_rows($q)>0){
			$sell_price=mysql_result(mysql_query("select max(buy_price) from $db->share"), 0) or 0;
			mysql_query("UPDATE $db->share SET status=1,sell_price=".$sell_price.",selling_datetime='".date('Y-m-d H:i:s')."' WHERE id=".$_GET['sell_id']);
		}
	}
	//20130302: change method
	//$count_sql = "SELECT count(*) FROM $db->share WHERE status>=1 AND uid=".$uid;
	//$record_sql = "SELECT * FROM $db->share WHERE status>=1 AND uid=".$uid." ORDER BY id LIMIT <%limit_start%>, <%limit%>";
	$count_sql = "SELECT count(*) FROM $db->share_trading_ledger WHERE type='sell' AND uid=".$uid;
	$record_sql = "SELECT * FROM $db->share_trading_ledger WHERE type='sell' AND uid=".$uid." ORDER BY cdate DESC LIMIT <%limit_start%>, <%limit%>";
	
}elseif($_GET['action']=="buy"){
	if($_GET['buy_id']>0){
		//$sql = "SELECT id, uid, sell_price, total_unit FROM $db->share WHERE status=1 AND (replica=0 OR uid=1) AND id=".$_GET['buy_id'];
		$sql = "SELECT id, uid, sell_price, total_unit FROM $db->share WHERE status=1 AND id=".$_GET['buy_id'];
		$q = mysql_query($sql);
		if(mysql_num_rows($q)>0){
			$share = mysql_fetch_assoc($q);
			$buyer_balance=mysql_result(mysql_query("select ewallet from gg_users where id=".$uid), 0) or 0;
			$buyer_balance1=mysql_result(mysql_query("select swallet from gg_users where id=".$uid), 0) or 0;
			$buyer_balance2=mysql_result(mysql_query("select mwallet from gg_users where id=".$uid), 0) or 0;
			$seller_balance=mysql_result(mysql_query("select ewallet from gg_users where id=".$share['uid']), 0) or 0;
			$seller_balance1=mysql_result(mysql_query("select swallet from gg_users where id=".$share['uid']), 0) or 0;
			
			$total_price = $share['sell_price']*$share['total_unit'];
			$cdate = date('Y-m-d H:i:s');
			if($buyer_balance2>=$total_price && $seller_balance1>=$share['total_unit']){				
				mysql_query("UPDATE $db->share SET status=2,sell_date='".$cdate."' WHERE id=".$_GET['buy_id']);
				$buyer_balance2-=$total_price;
				mysql_query("INSERT INTO $db->member_mwallet_record SET uid=".$uid.",type='debit',amount=".$total_price.",bal=".$buyer_balance2.",descr='Buy ordinary share #".$share['id'].". ".$share['total_unit']."x".$share['sell_price']."=".$total_price."',cdate='".date('Y-m-d H:i:s')."'");
				mysql_query("UPDATE $db->users SET mwallet=mwallet-".$total_price." WHERE id=".$uid);			
				$seller_balance1-=$share['total_unit'];
				mysql_query("INSERT INTO $db->member_swallet_record (uid, type, amount, bal, cdate) VALUES ('".$share['uid']."','debit','".$share['total_unit']."','".$seller_balance1."','".$cdate."')");
				mysql_query("UPDATE $db->users SET swallet=swallet-".$share['total_unit']." WHERE id=".$share['uid']);
				
				$total_unit_share = number_format($share['total_unit'],2,'.','');
				$trade_date  = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")+7, date("Y")));
				$bal=mysql_result(mysql_query("select swallet from $db->users where id=".$uid), 0) or 0;
				$bal+=$total_unit_share;
				mysql_query("INSERT INTO $db->share (uid, total_unit, buy_price, buy_date, trade_date) VALUES ('$uid','$total_unit_share','".$share['sell_price']."','".$cdate."','$trade_date')");
				mysql_query("INSERT INTO $db->member_swallet_record (uid, type, amount, bal, cdate) VALUES ('$uid','credit','$total_unit_share','$bal','".$cdate."')");
				mysql_query("UPDATE $db->users SET swallet=swallet+".$total_unit_share." WHERE id=".$uid);				
				/*
				$total_unit_share = number_format($share['total_unit']/5,2,'.','');
				for($i=1;$i<=5;$i++){
					$trade_date  = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")+($i*30), date("Y")));
					$bal=mysql_result(mysql_query("select swallet from $db->users where id=".$uid), 0) or 0;
					$bal+=$total_unit_share;
					mysql_query("INSERT INTO $db->share (uid, total_unit, buy_price, buy_date, trade_date) VALUES ('$uid','$total_unit_share','".$share['sell_price']."','".$cdate."','$trade_date')");
					mysql_query("INSERT INTO $db->member_swallet_record (uid, type, amount, bal, cdate) VALUES ('$uid','credit','$total_unit_share','$bal','".$cdate."')");
					mysql_query("UPDATE $db->users SET swallet=swallet+".$total_unit_share." WHERE id=".$uid);
				}
				*/
				
				$seller_balance+=$total_price;				
				mysql_query("INSERT INTO gg_member_ewallet_record SET uid=".$share['uid'].",type='credit',amount=".$total_price.",bal=".$seller_balance.",descr='Sell ordinary share. ".$share['total_unit']." X ".$share['sell_price']." = ".$total_price."',cdate='".date('Y-m-d H:i:s')."'");
				mysql_query("UPDATE $db->users SET ewallet=ewallet+".$total_price." WHERE id=".$share['uid']);
				
				// no more processing fees except IND
				if($user_info['user_detail']['country']=='IND'){
					$process_fee=$total_price*0.1;
					$seller_balance-=$process_fee;
					mysql_query("INSERT INTO gg_member_ewallet_record SET uid=".$share['uid'].",type='debit',amount=".$process_fee.",bal=".$seller_balance.",descr='Processing fees for sell ordinary share. ".$total_price." X 10% = ".$process_fee."',cdate='".date('Y-m-d H:i:s')."'");
					mysql_query("UPDATE $db->users SET ewallet=ewallet-".$process_fee." WHERE id=".$share['uid']);
				}
				/*no need maintain
				$seller_balance2=mysql_result(mysql_query("select mwallet from gg_users where id=".$share['uid']), 0) or 0;
				$total_price-=$process_fee;
				$maintain = $total_price*0.3;
				$seller_balance-=$maintain;
				$seller_balance2+=$maintain;				
				mysql_query("INSERT INTO $db->member_ewallet_record SET uid=".$share['uid'].",type='dedit',amount=".$maintain.",bal=".$seller_balance.",descr='Auto Maintain sell cash flow share. ".$total_price." X 30% = ".$maintain."',cdate='".$cdate."'");
				mysql_query("INSERT INTO $db->member_mwallet_record SET uid=".$share['uid'].",type='credit',amount=".$maintain.",bal=".$seller_balance2.",descr='Auto Maintain sell cash flow share. ".$total_price." X 30% = ".$maintain."',cdate='".$cdate."'");
				mysql_query("UPDATE $db->users set ewallet=ewallet-".$maintain.",mwallet=mwallet+".$maintain." where id=".$share['uid']);
				*/
				$errmsg = __("Successful buy ordinary share.");
				$errmsg=format_msg($errmsg);				
			}else{
				$errmsg = __("In-sufficient share trading point.");
				$errmsg=format_err($errmsg);
			}			
		}
	}
	
	//20130302: change method
	//$count_sql = "SELECT count(*) FROM $db->share WHERE status=1";
	//$record_sql = "SELECT * FROM $db->share WHERE status=1 ORDER BY selling_datetime LIMIT <%limit_start%>, <%limit%>";
	$count_sql = "SELECT count(*) FROM $db->share_trading_ledger WHERE type='buy' AND uid=".$uid;
	$record_sql = "SELECT * FROM $db->share_trading_ledger WHERE type='buy' AND uid=".$uid." ORDER BY cdate DESC LIMIT <%limit_start%>, <%limit%>";
	
}


//tab
$css="<link rel='stylesheet' type='text/css' href='".CSS_URL."/tab/tab".(USER_BROWSER=='msie'? "-ie" : "").".css' />\n";

$result = mysql_query("select share_price from gg_share_target where balance>sell_balance or balance>buy_balance order by share_price limit 1") or 0;
if($result)
while($row = mysql_fetch_row($result))
{
	$current_price = $row[0];
}

$result = mysql_query("select share_price from gg_share_target where (balance>sell_balance or balance>buy_balance) and share_price<>".$current_price." order by share_price limit 1") or 0;
if($result)
while($row = mysql_fetch_row($result))
{
	$next_price = $row[0];
}

$result = mysql_query("select price from gg_share_trading_ledger where date_format(cdate,'%Y-%m-%d')='".date('Y-m-d')."' order by price limit 1") or 0;
if($result)
while($row = mysql_fetch_row($result))
{
	$low_price = $row[0];
}

$result = mysql_query("select price from gg_share_trading_ledger where date_format(cdate,'%Y-%m-%d')='".date('Y-m-d')."' order by price desc limit 1") or 0;
if($result)
while($row = mysql_fetch_row($result))
{
	$high_price = $row[0];
}

$result = mysql_query("select sum(match_qty) from gg_share_trading where match_qty>0 and date_format(cdate,'%Y-%m-%d')='".date('Y-m-d')."'") or 0;
if($result)
while($row = mysql_fetch_row($result))
{
	$volumn = $row[0];
}

$tab = $css.
"
<table class='pbl_table'>	
	<tr class='pbl_header'>	 
		<td style='vertical-align:middle'>".__("Ordinary Share Price")."</td>
		<td style='vertical-align:middle'>".__("Next Ordinary Share Price")."</td>
		<td style='vertical-align:middle'>".__("Trading Price")."</td>
		<td style='vertical-align:middle'>".__("Next Trading Price")."</td>
		<td style='vertical-align:middle'>".__("High")."</td>
		<td style='vertical-align:middle'>".__("Low")."</td>
		<td style='vertical-align:middle'>".__("Volumn")."</td>
	</tr>
	<tr class='row1'>
		<td class='number' width='160'>
			<div id='glyphs'><p><font color='black'>".number_format('0.105',3)."</font></p></div>
		</td>
		<td class='number' width='160'>
			<div id='glyphs'><p><font color='red'>".number_format('0.110',3)."</font></p></div>
		</td>
		<td class='number' width='160'>
			<div id='glyphs'><p><font color='black'>".number_format($current_price,3)."</font></p></div>
		</td>
		<td class='number' width='160'>
			<div id='glyphs'><p><font color='red'>".number_format($next_price,3)."</font></p></div>
		</td>		
		<td class='number' width='160'>
			<div id='glyphs'><p><font color='black'>".number_format($high_price,3)."</font></p></div>
		</td>		
		<td class='number' width='160'>
			<div id='glyphs'><p><font color='black'>".number_format($low_price,3)."</font></p></div>
		</td>
		<td class='number' width='160'>
			<div id='glyphs'><p><font color='black'>".number_format($volumn,0,'','')."</font></p></div>
		</td>
	</tr>
</table>
<br>
";

$available_ewallet = mysql_result(mysql_query("select ewallet from $db->users where id=".$uid), 0) or 0;
$available_trading_point = mysql_result(mysql_query("select mwallet from $db->users where id=".$uid), 0) or 0;
$available_share = mysql_result(mysql_query("select swallet from $db->users where id=".$uid), 0) or 0;
$available_balance = mysql_result(mysql_query("select balance-buy_balance from gg_share_target where balance>buy_balance order by share_price limit 1"), 0) or 0;

/* no traffic jam no need to lock price
 * $share_price = mysql_result(mysql_query("select share_price from gg_share_target where balance=buy_balance order by share_price desc limit 1"), 0) or 0;
$num_record = @mysql_num_rows($r=mysql_query("select share_price from gg_share_target where sell_balance<balance and buy_balance=balance and share_price=".$share_price));
if($num_record>0)
	$available_balance = 0;
*/
$tab.=
"<input type='hidden' id='buy_balance' name='buy_balance' value='$available_balance' />
<table width='100%'><tr>

<td align='right' width='100%'>
<table class='pbl_table'>
	
	 <tr class='pbl_header'>
	 
	  <td>".__("Total Target")."</td>

	  <td>".__("Total Sell Units")."</td>

	  <td>".__("Total Buy Units")."</td>
	
	  <td>".__("Price")."</td>
	
	 </tr>	 

";
$sql = "SELECT * FROM gg_share_target WHERE balance>buy_balance or balance>sell_balance ORDER BY share_price LIMIT 8";
$share_rs = mysql_query($sql);
$k=0;
$last_share_price = 0;
while($share_record = mysql_fetch_assoc($share_rs)){
	$tab .= "<tr class='row$k'><td class='number'>".number_format($share_record['balance'],0)."</td><td class='number'>".number_format($share_record['sell_balance'],0)."</td><td class='number'>".number_format($share_record['buy_balance'],0)."</td><td class='number'>".number_format($share_record['share_price'],3)."</td></tr>";
	$k=1-$k;
	$last_share_price = $share_record['share_price'];
}


$tab .=
"
</table><br>

<font color='black'>
<form id='trade_form' name='trade_form' method='post' action='$this_file' onsubmit='return validate(this);'>
<table border='1' width='100%' bgcolor='#FFFFFF'><tr><td>
<table>
<tr><td>
<input type='radio' name='trade_type' value=\"buy\" id='buy' class='no_bg' onclick='displayprice()' checked/><label for='buy'><font color='black'><b>".__("Buy")."</b></font></label>
<input type='radio' name='trade_type' value=\"sell\" id='sell' class='no_bg' onclick='displayprice()' /><label for='sell'><font color='black'><b>".__("Sell")."</b></font></label>
</td></tr>
<tr><td><table cellpadding='0'><tr><td>
<font color='black'><b>".__("Quantity")."</b></font></td><td>&nbsp;<input type='text' id='qty' name='qty' value='' class='inputbox' onkeypress='return digits(this, event, false, false);'/></td><td><div id='divprice2' name='divprice2' style='display:none'><font color='black'>(".__("available quantity")." ".number_format($available_share,0).")</font></div><div id='divprice4' name='divprice4' style='display:'></div></td></tr></table>
</td><td>";

$this_page_total=@mysql_num_rows($r=mysql_query("select share_price from gg_share_target where balance>sell_balance order by share_price limit 8"));

$tab.="<div id='divprice' name='divprice' style='display:none'>&nbsp;<font color='black'><b>".__("Price")."</b></font>&nbsp;<select id='price' name='price'>";
for($i=0;$i<$this_page_total;$i++){
	$p=mysql_fetch_assoc($r);
	
	if($p['share_price']>$last_share_price) break;
	
	$tab.="<option value='".$p['share_price']."'>".$p['share_price']."</option>";
}
$tab.="</select></div>";

$this_page_total=@mysql_num_rows($r=mysql_query("select share_price from gg_share_target where balance>buy_balance order by share_price limit 8"));
$tab.="<div id='divprice3' name='divprice3' style='display:'>&nbsp;<font color='black'><b>".__("Price")."</b></font>&nbsp;<select id='buy_price' name='buy_price'>";
for($i=0;$i<$this_page_total;$i++){
	$p=mysql_fetch_assoc($r);
	
	if($p['share_price']>$last_share_price) break;
	
	$tab.="<option value='".$p['share_price']."'>".$p['share_price']."</option>";
}
$tab.="</select></div>";

$tab.="
</td><td><div id='divpayment' name='divpayment' style='display:'>&nbsp;<font color='black'><b>".__("Payment Mode")."</b></font>&nbsp;";

$tab.="<select id='payment' name='payment'>
<option value='mwallet'>".__('Share Trading Point')." (".$available_trading_point.")</option>
<option value='ewallet'>".__('e-Wallet')." (".$available_ewallet.")</option>
</select>";

$sell_limit = mysql_result(mysql_query("select incentive_unit*0.05 from gg_users where id=".$uid), 0) or 0;
$sell_limit = number_format($sell_limit,0,'','');
if($sell_limit<100) $sell_limit = 100;
$sell_queue = mysql_result(mysql_query("select count(*) from gg_share_trading where type='sell' and qty<>match_qty and uid=".$uid), 0) or 0;
$result = mysql_query("select count(*) from gg_share_trading where type='sell' and date_format(cdate, '%Y-%m-%d')='".date('Y-m-d')."' uid=".$uid) or 0;
if($result)
while($row = mysql_fetch_row($result))
{
	$ttl_sell = $row[0];
}
if($uid==1) $sell_queue = 0;

$tab.="
</div></td></tr>
<tr><td>
<input type='hidden' id='__trade' name='__trade' value='1' />
<input type='hidden' id='limit' name='limit' value='".$sell_limit."' />
<input type='hidden' id='queue' name='queue' value='".$sell_queue."' />
<input type='hidden' id='ttl_sell' name='queue' value='".$ttl_sell."' />
<input type='hidden' id='msg1' name='msg1' value='".__("Please select buy or sell")."' />
<input type='hidden' id='msg2' name='msg2' value='".__("Please enter quantity")."' />
<input type='hidden' id='msg3' name='msg3' value='".__("Please enter price")."' />
<input type='hidden' id='msg4' name='msg4' value='".__("Do you really want to submit?")."' />
<input type='hidden' id='msg5' name='msg5' value='".__("Quantity must be at least 100")."' />
<input type='hidden' id='msg6' name='msg6' value='".__("Cannot queue more than 1 sell transaction")."' />
<input type='hidden' id='msg7' name='msg7' value='".__("Quantity cannot more than")." ".$sell_limit."' />
<input type='hidden' id='msg8' name='msg8' value='".__("You only allow to sell 5 times per day")."' />";



$tab.="<div id='divpayment5' name='divpayment5' style='display:".($available_balance==0?'none':'')."'><input type='submit' name='submit_btn' value='".__("Submit")."' /></div><div id='divpayment6' name='divpayment6' style='display:".($available_balance==0?'':'none')."'><font color='red'>".__('Need to wait first target price finish sell')."</font></div>";

$tab.="<font color='red'>".$msg."</font>
</td></tr>
</table>
</td></tr></table>
</form>
";

$tab .= 
"</td></tr></table>
";


$tab.=
"<ul class='tabs-nav' id='_tab'>
  <li class='tabs-".($_GET['action']=='trade' || $_GET['action']=='cancel_order' || !$_GET['action']? "" : "un")."selected' rel='list'><a href='".$vars['file']['member']['cash_flow_program']."?action=trade'><span>".__("Order Status Listing")."</span></a></li>
  <li class='tabs-".($_GET['action']=='share'? "" : "un")."selected' rel='list'><a href='".$vars['file']['member']['cash_flow_program']."?action=share'><span>".__("Share Lock-Off Period Listing")."</span></a></li>
  <li class='tabs-".($_GET['action']=='sell'? "" : "un")."selected' rel='sell'><a href='".$vars['file']['member']['cash_flow_program']."?action=sell'><span>".__("Sell Listing")."</span></a></li>
  <li class='tabs-".($_GET['action']=='buy'? "" : "un")."selected' rel='buy'><a href='".$vars['file']['member']['cash_flow_program']."?action=buy'><span>".__("Buy Listing")."</span></a></li>
</ul>
<div class='tabs-panel' style='width:97%;'><%tab_content%></div>";	


//#####LIST EWALLET HISTORY#####

$cur_page=$_GET["nav"];

$total_record=@mysql_result(mysql_query($count_sql), 0);

$total_page=ceil($total_record/$item_per_page);

$page=($cur_page? ($cur_page>$total_page? $total_page : ($cur_page<1? 1 : $cur_page)) : 1);

$limit_start=($page-1)*$item_per_page;

$nav_link=format_page($page, $total_page, 15);

$this_page_total=@mysql_num_rows($r=mysql_query(str_replace("<%limit_start%>", $limit_start, str_replace("<%limit%>", $item_per_page, $record_sql))));

$k=0;

$is_free = @mysql_result(mysql_query("select is_free from $db->users where id='$uid'"), 0) or 0;

if($_GET['action']=="trade" || $_GET['action']=="cancel_order" || !$_GET['action']){
	
	for($i=0;$i<$this_page_total;$i++){
	
		$p=mysql_fetch_assoc($r);
		
		if($p['match_qty']>0)
			$link = "";
		else
			$link = "<a href='".$vars['file']['member']['cash_flow_program']."?action=cancel_order&order_id=$p[id]' onclick=\"return confirm('".__("Are you sure you want to cancel order?")."')\">".__("Cancel Order")."</a>";
				
		$his_row.="
		
			<tr class='row$k'>
		
		  	<td>".($i+1)."</td>
		
		  	<td>".__($p['type'])."</td>
		
		  	<td class='number'>".number_format($p['price'],4)."</td>
		
		  	<td class='number'>".number_format($p['qty'],0)."</td>
		  	
		  	<td class='number'>".number_format($p['match_qty'],0)."</td>
		
		  	<td>".date($vars['date_format'], strtotime($p['cdate']))."</td>
		  	
		  	<td>".$link."</td>
		  			
		 	</tr>";		
		
	 	$k=1-$k;
	}
	
}elseif($_GET['action']=="share"){
		
	for($i=0;$i<$this_page_total;$i++){
	
		$p=mysql_fetch_assoc($r);
		
		if($p['trade_date']<=date('Y-m-d') && $is_free==0)
			$link = "<a href='".$vars['file']['member']['cash_flow_program']."?action=sell&sell_id=$p[id]' onclick=\"return confirm('".__("Are you sure you want to sell?")."')\">".__("Sell")."</a>";
		else
			$link = __("Pending");
		
		$his_row.="
		
			<tr class='row$k'>
		
		  	<td>".($i+1)."</td>
		
		  	<td class='number'>".number_format($p['buy_price'],4)."</td>
		
		  	<td class='number'>".number_format($p['total_unit'],0)."</td>
		
		  	<td>".date($vars['date_format'], strtotime($p['buy_date']))."</td>
		
		  	<td>".date($vars['date_format'], strtotime($p['trade_date']))."</td>
		
		 	</tr>";		
		
	 	$k=1-$k;
	}

}elseif($_GET['action']=="sell" || $_GET['action']=="buy"){

	for($i=0;$i<$this_page_total;$i++){
	
		$p=mysql_fetch_assoc($r);
		
		$his_row.="
		
			<tr class='row$k'>
		
		  	<td>".($i+1)."</td>
		
		  	<td class='number'>".number_format($p['price'],4)."</td>

		  	<td class='number'>".number_format($p['qty'],0)."</td>
		
		  	<td>".date($vars['date_format'], strtotime($p['cdate']))."</td>
		
		 	</tr>";
		 	
		 $k=1-$k;

	}
	
}

//listing text

$listing_text=replace_tag(__("<%x%> <%title%> <%record%>."), array("<%x%>"=>"$total_record", "<%title%>"=>__("Cash Flow Program"), "<%record%>"=>$total_record>1? __("records") : __("record")));



//listing
if($_GET['action']=="trade" || $_GET['action']=="cancel_order" || !$_GET['action']){
	
	$his_list=

	"<h2>".replace_tag(__("<%title%> History"), array("<%title%>"=>__("Order Status")))."</h2>
	
	$listing_text<br>$nav_link
	
	<table class='pbl_table'>
	
	 <tr class='pbl_header'>
	
	  <td>".__("Trans#")."</td>
	  
	  <td>".__("Type")."</td>
	
	  <td>".__("Price")."</td>
	
	  <td>".__("Quantity")."</td>
	
	  <td>".__("Match Quantity")."</td>
	
	  <td>".__("Created Date")."</td>
	  		
	  <td></td>
	  
	 </tr>
	
	 $his_row
	
	</table>
	
	$nav_link";
	
}elseif($_GET['action']=="share"){
	
	$his_list=

	"<h2>".replace_tag(__("<%title%> History"), array("<%title%>"=>__("Ordinary Share Lock-Off")))."</h2>
	
	$listing_text<br>$nav_link
	
	<table class='pbl_table'>
	
	 <tr class='pbl_header'>
	
	  <td>".__("Trans#")."</td>
	
	  <td>".__("Purchase Price")."</td>
	
	  <td>".__("Quantity")."</td>
	
	  <td>".__("Purchase Date")."</td>
	
	  <td>".__("Lock-Off Period")."</td>
	  
	 </tr>
	
	 $his_row
	
	</table>
	
	$nav_link";	
	
}elseif($_GET['action']=="sell"){

	$his_list=

	"<h2>".replace_tag(__("<%title%> History"), array("<%title%>"=>__("Ordinary Share Sell")))."</h2>
	
	$listing_text<br>$nav_link
	
	<table class='pbl_table'>
	
	 <tr class='pbl_header'>
	
	  <td>".__("Trans#")."</td>

	  <td>".__("Share Price")."</td>
	
	  <td>".__("Quantity")."</td>
	
	  <td>".__("Selling Date")."</td>
	  
	 </tr>
	
	 $his_row
	
	</table>
	
	$nav_link";

}elseif($_GET['action']=="buy"){

	$his_list=

	"<h2>".replace_tag(__("<%title%> History"), array("<%title%>"=>__("Ordinary Share Buy")))."</h2>
	
	$listing_text<br>$nav_link
	
	<table class='pbl_table'>
	
	 <tr class='pbl_header'>
	
	  <td>".__("Trans#")."</td>

	  <td>".__("Share Price")."</td>
	
	  <td>".__("Quantity")."</td>
	
	  <td>".__("Selling Date")."</td>
	
	 </tr>
	
	 $his_row
	
	</table>
	
	$nav_link";
	
}

/* change trading methond
$share_trade = 
"
<table><tr><td valign='top'>
<table class='pbl_table'>
	
	 <tr class='pbl_header'>
	 
	  <td>".__("B/Queue")."</td>

	  <td>".__("B/Qty")."</td>

	  <td>".__("Buy")."</td>
	
	  <td>".__("Sell")."</td>
	
	  <td>".__("S/Qty")."</td>
	  
	  <td>".__("S/Queue")."</td>
	
	 </tr>	 

";

$k=0;
for($i=1;$i<=5;$i++){
	$share_trade .= "<tr class='row$k'><td class='number'>".number_format($buy_arr[$i]['count'],0)."</td><td class='number'>".number_format($buy_arr[$i]['qty'],0)."</td><td class='number'>".number_format($buy_arr[$i]['price'],4)."</td><td class='number'>".number_format($sell_arr[$i]['price'],4)."</td><td class='number'>".number_format($sell_arr[$i]['qty'],0)."</td><td class='number'>".number_format($sell_arr[$i]['count'],0)."</td></tr>";
	$k=1-$k;
}

*/

$content=$errmsg.$his_list;

//$content="<h2>$page_title</h2>$matrix";
$content=str_replace("<%tab_content%>", $content, $tab);
$content='<div style="margin:13px;font-size:14px;color:#F9EF7C;font-family:Lucida Sans;background-color:#111;width:180px;z-index:4;position:absolute;text-align:center;">'.$page_title.'</div>
<div id="rounded" style="margin:0px auto;padding:10px;position:relative;float:inherit;width:750px;border:2px solid #F9EF7C;color:#F9EF7C;"><br>'.$content;

print format_member_page($content, $this_title, $content_title, $css . $inc_jvscript);

?>
